import React, { useState } from 'react';
import { Card, Table, Button, Input, Select, Space, Pagination, Modal, Descriptions } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';

const { Option } = Select;

export default function CustomerManage() {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const navigate = useNavigate();
  const location = useLocation();
  // initialData 移到组件内部
  const initialData = [
    { key: 1, name: '王晓涛', intentionLevel: '高', customerLevel: '一级', followStatus: '成交', follower: '约翰', createTime: '2020-05-17', lastFollowTime: '2022-01-23' },
    { key: 2, name: '张晓云', intentionLevel: '中', customerLevel: '二级', followStatus: '流失', follower: '杰克', createTime: '2020-08-17', lastFollowTime: '2022-01-23' },
    { key: 3, name: '王晓飞', intentionLevel: '高', customerLevel: '一级', followStatus: '意向', follower: '李雷', createTime: '2021-08-02', lastFollowTime: '2022-01-23' },
  ];
  const [tableData, setTableData] = useState(initialData);
  // 新增：增加searchForm状态
  const [searchForm, setSearchForm] = useState({
    name: '',
    intentionLevel: '',
    customerLevel: '',
    followStatus: ''
  });
  // 详情弹窗状态
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentDetail, setCurrentDetail] = useState(null);
  // 新增客户后自动添加
  React.useEffect(() => {
    if (location.state && location.state.newCustomer) {
      setTableData(prev => [location.state.newCustomer, ...prev]);
      window.history.replaceState({}, document.title);
    }
  }, [location.state]);

  // 新增：查询功能（任一条件匹配）
  const handleSearch = () => {
    const { name, intentionLevel, customerLevel, followStatus } = searchForm;
    if (!name && !intentionLevel && !customerLevel && !followStatus) {
      setTableData(initialData);
      return;
    }
    const filtered = initialData.filter(item => {
      return (
        (name && item.name.includes(name)) ||
        (intentionLevel && item.intentionLevel === intentionLevel) ||
        (customerLevel && item.customerLevel === customerLevel) ||
        (followStatus && item.followStatus === followStatus)
      );
    });
    setTableData(filtered);
  };
  // 新增：重置功能
  const handleReset = () => {
    setSearchForm({ name: '', intentionLevel: '', customerLevel: '', followStatus: '' });
    setTableData(initialData);
  };
  // 单个删除功能
  const handleDelete = (key) => {
    setTableData(prev => prev.filter(item => item.key !== key));
  };
  // 批量删除功能
  const handleBatchDelete = () => {
    setTableData(prev => prev.filter(item => !selectedRowKeys.includes(item.key)));
    setSelectedRowKeys([]);
  };
  // columns定义移到组件内部，确保可以访问handleDelete
  const columns = [
    { title: '客户名称', dataIndex: 'name', key: 'name', width: 180 },
    { title: '意向等级', dataIndex: 'intentionLevel', key: 'intentionLevel', width: 100 },
    { title: '客户等级', dataIndex: 'customerLevel', key: 'customerLevel', width: 100 },
    { title: '跟进状态', dataIndex: 'followStatus', key: 'followStatus', width: 100 },
    { title: '跟进人', dataIndex: 'follower', key: 'follower', width: 100 },
    { title: '新增时间', dataIndex: 'createTime', key: 'createTime', width: 120 },
    { title: '最近跟进时间', dataIndex: 'lastFollowTime', key: 'lastFollowTime', width: 120 },
    { title: '操作', key: 'action', width: 120, render: (_, record) => (
      <Space>
        <a onClick={() => { setCurrentDetail(record); setDetailVisible(true); }}>详情</a>
        <a style={{color:'#f5222d'}} onClick={() => handleDelete(record.key)}>删除</a>
      </Space>
    ) },
  ];
  return (
    <div style={{padding:32, background:'#f5f7fa', minHeight:'100vh'}}>
      <Card style={{maxWidth:1400, margin:'0 auto', borderRadius:12, boxShadow:'0 2px 8px rgba(0,0,0,0.04)'}}>
        <div style={{display:'flex', alignItems:'center', marginBottom:24}}>
          <Button onClick={()=>navigate('/dashboard/enterprise')} style={{marginRight:16, borderRadius:6}}>返回</Button>
          <div style={{fontWeight:700, fontSize:20, display:'flex', alignItems:'center'}}>
            <div style={{width:4, height:22, background:'#3B5BDB', borderRadius:2, marginRight:10}}></div>
            客户信息管理
          </div>
          <div style={{flex:1}}></div>
          <Button type="primary" style={{borderRadius:6, width:90, marginRight:8}} onClick={()=>navigate('/business/customer/create')}>新增</Button>
          <Button danger style={{borderRadius:6, width:110}} onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0}>批量删除</Button>
        </div>
        <div style={{marginBottom:20, display:'flex', gap:16, alignItems:'center', background:'#fafbfc', padding:'18px 18px 0 18px', borderRadius:8, flexWrap:'wrap'}}>
          <Input
            placeholder="请输入客户名称"
            style={{width:260, borderRadius:6, marginBottom:12}}
            allowClear
            value={searchForm.name}
            onChange={e => setSearchForm({ ...searchForm, name: e.target.value })}
          />
          <Select
            placeholder="请选择意向等级"
            style={{width:200, borderRadius:6, marginBottom:12}}
            allowClear
            value={searchForm.intentionLevel}
            onChange={value => setSearchForm({ ...searchForm, intentionLevel: value })}
          >
            <Option value="高">高</Option>
            <Option value="中">中</Option>
            <Option value="低">低</Option>
          </Select>
          <Select
            placeholder="请选择客户等级"
            style={{width:200, borderRadius:6, marginBottom:12}}
            allowClear
            value={searchForm.customerLevel}
            onChange={value => setSearchForm({ ...searchForm, customerLevel: value })}
          >
            <Option value="一级">一级</Option>
            <Option value="二级">二级</Option>
          </Select>
          <Select
            placeholder="请选择跟进状态"
            style={{width:200, borderRadius:6, marginBottom:12}}
            allowClear
            value={searchForm.followStatus}
            onChange={value => setSearchForm({ ...searchForm, followStatus: value })}
          >
            <Option value="成交">成交</Option>
            <Option value="流失">流失</Option>
            <Option value="意向">意向</Option>
          </Select>
          <Button type="primary" style={{borderRadius:6, width:90, marginBottom:12}} onClick={handleSearch}>查询</Button>
          <Button style={{borderRadius:6, width:90, marginBottom:12}} onClick={handleReset}>重置</Button>
        </div>
        <Table
          rowSelection={{selectedRowKeys,onChange:setSelectedRowKeys}}
          columns={columns}
          dataSource={tableData}
          pagination={false}
          bordered
          style={{background:'#fff', borderRadius:8, marginTop:16}}
        />
        {/* 客户详情弹窗 */}
        <Modal
          open={detailVisible}
          title="客户详情"
          footer={null}
          onCancel={() => setDetailVisible(false)}
          width={500}
        >
          {currentDetail && (
            <Descriptions column={1} bordered size="middle">
              <Descriptions.Item label="客户名称">{currentDetail.name}</Descriptions.Item>
              <Descriptions.Item label="意向等级">{currentDetail.intentionLevel}</Descriptions.Item>
              <Descriptions.Item label="客户等级">{currentDetail.customerLevel}</Descriptions.Item>
              <Descriptions.Item label="跟进状态">{currentDetail.followStatus}</Descriptions.Item>
              <Descriptions.Item label="跟进人">{currentDetail.follower}</Descriptions.Item>
              <Descriptions.Item label="新增时间">{currentDetail.createTime}</Descriptions.Item>
              <Descriptions.Item label="最近跟进时间">{currentDetail.lastFollowTime}</Descriptions.Item>
            </Descriptions>
          )}
        </Modal>
        <div style={{marginTop:24, textAlign:'right'}}>
          <Pagination total={100} pageSize={10} showSizeChanger={false} />
        </div>
      </Card>
    </div>
  );
} 